import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
// @ts-ignore
import { isLoggedIn } from '@/utils/auth'

const routes: RouteRecordRaw[] = [
  // 默认重定向到登录页面
  {
    path: '/',
    redirect: '/ai-login'
  },
  // AI 登录首页（新的默认入口）
  {
    path: '/ai-login',
    name: 'AiLogin',
    component: () => import('@/views/VoiceCall/Ailogin.vue'),
    meta: { title: 'AI智能家教登录', requiresGuest: true }
  },
  // 人脸登录页面
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/FaceLogin.vue'),
    meta: { title: '人脸登录', requiresGuest: true }
  },
  // 人脸注册页面
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/FaceRegister.vue'),
    meta: { title: '人脸注册', requiresGuest: true }
  },
  // 主应用布局
  {
    path: '/home',
    component: () => import('@/components/Layout/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      // 首页 - 显示原来的AI功能页面
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/AiFeatures/index.vue'),
        meta: { title: 'AI智能助手' }
      },
      // 相机功能页面 - 集成S0806的MainApp
      {
        path: 'camera',
        name: 'Camera',
        component: () => import('@/views/CameraApp.vue'),
        meta: { title: 'AI学习助手' }
      },
      // 个人中心页面
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心' }
      }
    ]
  },
  // 语音通话页面（独立页面，不在主布局中）
  {
    path: '/voice-call',
    name: 'VoiceCall',
    component: () => import('@/views/VoiceCall/index.vue'),
    meta: { title: '语音通话', requiresAuth: true }
  },
  // 数字人通话页面（独立页面，不在主布局中）
  {
    path: '/digital-human',
    name: 'DigitalHuman',
    component: () => import('@/views/DigitalHuman/index.vue'),
    meta: { title: '数字人通话', requiresAuth: true }
  },
  // AI功能页面路由（保持原有功能）
  {
    path: '/ai-features/knowledge-qa',
    name: 'KnowledgeQA',
    component: () => import('@/views/AiFeatures/KnowledgeQA.vue'),
    meta: { title: '知识问答', requiresAuth: true }
  },
  {
    path: '/ai-features/information-query',
    name: 'InformationQuery',
    component: () => import('@/views/AiFeatures/InformationQuery.vue'),
    meta: { title: '信息查询', requiresAuth: true }
  },
  {
    path: '/ai-features/text-generation',
    name: 'TextGeneration',
    component: () => import('@/views/AiFeatures/TextGeneration.vue'),
    meta: { title: '文本生成', requiresAuth: true }
  },
  {
    path: '/ai-features/translation',
    name: 'Translation',
    component: () => import('@/views/AiFeatures/Translation.vue'),
    meta: { title: '语言翻译', requiresAuth: true }
  },
  {
    path: '/ai-features/emotional-companion',
    name: 'EmotionalCompanion',
    component: () => import('@/views/AiFeatures/EmotionalCompanion.vue'),
    meta: { title: '情感陪伴', requiresAuth: true }
  },
  {
    path: '/ai-features/recommendation',
    name: 'Recommendation',
    component: () => import('@/views/AiFeatures/Recommendation.vue'),
    meta: { title: '智能推荐', requiresAuth: true }
  },
  {
    path: '/ai-features/game-entertainment',
    name: 'GameEntertainment',
    component: () => import('@/views/AiFeatures/GameEntertainment.vue'),
    meta: { title: '游戏娱乐', requiresAuth: true }
  },
  {
    path: '/ai-features/health-management',
    name: 'HealthManagement',
    component: () => import('@/views/AiFeatures/HealthManagement.vue'),
    meta: { title: '健康管理', requiresAuth: true }
  },
  {
    path: '/ai-features/image-generation',
    name: 'ImageGeneration',
    component: () => import('@/views/AiFeatures/ImageGeneration.vue'),
    meta: { title:'AI文生图', requiresAuth: true }
  },
  // API测试页面
  {
    path: '/api-test',
    name: 'ApiTest',
    component: () => import('@/views/ApiTest/index.vue'),
    meta: { title: 'API连接测试', requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 首次进入时强制到登录页（即使已登录也进入登录页）
let firstEnter = true

// 路由守卫 - 认证和页面标题
router.beforeEach((to, from, next) => {
  const loggedIn = isLoggedIn()

  // 首次进入强制到登录页
  if (firstEnter) {
    firstEnter = false
    if (to.path !== '/ai-login') {
      next('/ai-login')
      return
    }
  }

  // 设置页面标题
  if (to.meta?.title) {
    document.title = to.meta.title as string
  }

  // 需要登录的页面
  if (to.meta?.requiresAuth && !loggedIn) {
    next('/ai-login')
    return
  }

  // 只允许游客访问的页面（如登录、注册）
  if (to.meta?.requiresGuest && loggedIn) {
    // 已登录时也允许访问这些页面，方便切换到人脸登录/注册
    const allowWhileLoggedIn = ['/ai-login', '/login', '/register']
    if (allowWhileLoggedIn.includes(to.path)) {
      next()
    } else {
      next('/home')
    }
    return
  }

  next()
})

export default router
